<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useEmitt } from '@/hooks/web/useEmitt'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { useLocaleStore } from '@/store/modules/locale'
import { EntityDialog } from '@/components/Dialog'
import { getZhHKAndPinyin, getZhCNAndPinyin } from '@/api/common'
import { selectModule } from '@/api/develop'
import { saveDataList, publishDataList, getDataList, getListSQL } from '@/api/develop/list'
import { getFormsByEntId } from '@/api/develop/form'
import { getDataTypes } from '@/api/develop/entity'
import { EntityTree } from '@/components/Tree'

defineOptions({
  name: 'ListEdit'
})

const localeStore = useLocaleStore()
const { t } = useI18n()
const { emitter } = useEmitt()
const formRef = ref()
const { currentRoute, push } = useRouter()

const state = reactive({
  // 数据列表表单数据
  formData: {
    seq: 0,
    ver: 0,
    canSelectMore: 0,
    endType: 1,
    isBuildIn: 0,
    isLazy: 0,
    isPaging: 1,
    listType: 0,
    showHighFilter: 0,
    showQueryPlan: 0,
    showSerialNo: 1,
    status: 0,
    pageSize: 10,
    id: null,
    clickEvent: '',
    copyFrom: '',
    dblClickEvent: '',
    entId: '',
    enName: '',
    hkName: '',
    icon: '',
    lineHeight: '',
    mainTableName: '',
    mbFormId: '',
    mbFormReadId: '',
    moduleId: '',
    name: '',
    pcFormId: '',
    pcFormReadId: '',
    remark: '',
    settings: '',
    sqlAfterDel: '',
    sqlBeforeDel: '',
    sqlJoin: '',
    sqlOderBy: '',
    sqlWhere: '',
    beforeSql: '',
    moduleName: '',
    hkModuleName: '',
    enModuleName: '',
    entName: '',
    hkEntName: '',
    enEntName: '',
    createTime: null,
    createBy: '',
    updateTime: null,
    updateBy: '',
    cols: [{} as any]
  },
  deleteIds: [{}],

  // 校验规则
  formRules: {
    name: {
      required: true,
      message: t('dataList.name') + t('common.notEmpty'),
      trigger: ['blur']
    },
    moduleId: [
      {
        required: true,
        message: t('orderNo.module') + t('common.notEmpty'),
        trigger: ['blur', 'change']
      }
    ],
    entId: [
      {
        required: true,
        message: t('dataList.mainEntity') + t('common.notEmpty'),
        trigger: ['blur', 'change']
      }
    ]
  },
  formDialogVisible: false,
  entityDialogVisible: false,
  defaultShowPanels: ['1', '2'],
  modNameField: 'moduleName',
  entityNameField: 'entName',
  dataListNameField: 'name',
  formNameField: 'fmName',
  moduleList: [{} as any],
  pcFormList: [{} as any],
  mbFormList: [{} as any],
  dataTypes: [{} as any],
  endTypeOptions: [
    { value: 1, label: 'PC' },
    { value: 2, label: t('menu.clientType2') },
    { value: 3, label: t('menu.clientType3') }
  ],
  curRow: {} as any,
  loading: false,
  publishLoading: false,
  fromPath: '',
  initColIds: ['']
})

//加载事件
onMounted(async () => {
  state.moduleList = await selectModule()
  state.dataTypes = await getDataTypes()
  //当前语言
  const curLang = localeStore.getCurrentLocale.lang
  if (curLang == 'en') {
    state.modNameField = 'enModuleName'
    state.dataListNameField = 'enName'
    state.entityNameField = 'enEntName'
    state.formNameField = 'enName'
  } else if (curLang == 'zh_HK') {
    state.modNameField = 'hkModuleName'
    state.dataListNameField = 'hkName'
    state.entityNameField = 'hkEntName'
    state.formNameField = 'hkName'
  }
  init()
})

//根据模块变化刷新数据源
const refreshFormList = async (event) => {
  const entId = event
  if (!entId || entId.length == 0) {
    return
  }
  const formList = (await getFormsByEntId(entId)).data
  state.pcFormList = formList.filter((item) => item.fmType == 1)
  state.mbFormList = formList.filter((item) => item.fmType == 2)
  formRef.value.clearValidate(['mbFormId', 'mbFormReadId', 'pcFormId', 'pcFormReadId'])
  // 校验表单是否与实体匹配
  checkFormId(state.pcFormList, state.formData.pcFormId)
  checkFormId(state.pcFormList, state.formData.pcFormReadId)
  checkFormId(state.mbFormList, state.formData.mbFormId)
  checkFormId(state.mbFormList, state.formData.mbFormReadId)
}

//检查表单列表中是否包含指定值,如果不包含则设为空
const checkFormId = (list, formId) => {
  if (!list || !formId) {
    formId = ''
    return
  }
  for (let fm of list) {
    if (fm.fmId == formId) {
      return
    }
  }
  formId = ''
}

//选中关联实体
const selectEntity = (data) => {
  const oldEntId = state.formData.entId
  state.formData.entId = data.pkId
  state.formData.entName = data.entName
  state.formData.hkEntName = data.hkName
  state.formData.enEntName = data.enName
  state.entityDialogVisible = false
  if (oldEntId != data.pkId) {
    refreshFormList(state.formData.entId)
    delRelatedCols()
    state.initColIds = []
  }
}

//更换实体时，清除实体关联的列
const delRelatedCols = () => {
  let newCols = []
  for (const col of state.formData.cols) {
    if (!col.entityColId) {
      newCols.push(col)
    }
  }
  state.formData.cols = newCols
}

//点击选择引用实体
const click2SelectEnt = () => {
  if (state.formData.cols.length > 0) {
    ElMessageBox.confirm(t('dataList.entChangeTips'), t('common.reminder'), {
      confirmButtonText: t('common.ok'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    })
      .then(() => {
        state.entityDialogVisible = true
        return
      })
      .catch(() => {
        return
      })
  } else {
    state.entityDialogVisible = true
  }
}

//清空引用实体
const clearEnt = () => {
  state.formData.entId = ''
  state.formData.entName = ''
  state.formData.hkEntName = ''
  state.formData.enEntName = ''
  state.formData.pcFormId = ''
  state.formData.pcFormReadId = ''
  state.formData.mbFormId = ''
  state.formData.mbFormReadId = ''
}

//删除列表字段
const deleteRow = (row, index) => {
  const id = row.id
  if (id && id.length > 0) {
    state.deleteIds.push(id)
  }
  let i = index
  if (!index) {
    i = getRowIndex(row.fieldName, row.tableAlias)
  }
  console.log('删除字段：' + row.fieldName + '@' + i)
  state.formData.cols.splice(i, 1)
}
//定位要删除字段行的下标
const getRowIndex = (fieldName, tableAlias) => {
  const length = state.formData.cols.length
  for (let i = 0; i < length; i++) {
    const col = state.formData.cols[i] as any
    if (col.fieldName == fieldName && col.tableAlias == tableAlias) {
      return i
    }
  }
  return -1
}

const getDefaultRow = () => {
  const newIndex = state.formData.cols.length + 1
  let row = {
    seq: 0,
    colOrder: newIndex,
    isExport: 1,
    isFilter: 1,
    isFixed: 0,
    isFk: 0,
    isLink: 0,
    isSort: 0,
    isMobile: 0,
    textAlign: 0,
    id: null,
    bgColor: '',
    colType: 'decimal',
    colWidth: '',
    dataFormat: '',
    entityColId: '',
    fieldName: 'fieldName' + newIndex,
    fieldAlias: 'fieldAlias' + newIndex,
    fontColor: '',
    fontSize: '',
    headerEn: '',
    headerHk: '',
    headerText: '',
    linkUrl: '',
    listId: null,
    dictId: null,
    others: '',
    parentHeaderId: '',
    statFunc: '',
    tableAlias: ''
  }
  return row
}

//新增默认字段
const addRow = () => {
  const row = getDefaultRow()

  state.formData.cols.push(row)
}

//发布数据列表
const publish = async () => {
  const tips = t('entity.publishTip2')
  ElMessageBox.confirm(tips, t('entity.confirm'), {
    type: 'warning'
  }).then(() => {
    state.publishLoading = true
    publishDataList(state.formData.id).then((res) => {
      const result = res as any
      state.publishLoading = false
      if (!res) {
        return
      }
      //发布成功
      if (result.success) {
        //刷新列表
        emitter.emit('refreshDataViewList', 'edit')
        if (result.message != 'entity.manually') {
          ElMessage.success(t(result.message))
          goBack()
          return
        }
      }
    })
  })
}

//预览数据列表
const preview = (id) => {
  push({
    name: 'ListShow',
    query: {
      listId: id,
      preview: 1,
      fromPath: currentRoute.value.fullPath
    }
  })
}

//查看SQL
const showSql = () => {
  formRef.value.validate(async (vaild) => {
    if (!vaild) {
      return
    }
    //校验明细记录
    if (!state.formData.cols || state.formData.cols.length == 0) {
      ElMessage.warning(t('entity.noFields'))
      return
    }
    for (let row2 of state.formData.cols) {
      const row = row2 as any
      if (row.showName == '' || row.fieldName == '') {
        ElMessage.warning(t('dataDict.rowCheck'))
        return
      }
    }
    if (nameIsRepeat()) {
      ElMessage.warning(t('dataList.repeatFieldName'))
      return
    }

    let data = { dataList: state.formData }
    await getListSQL(data).then((res) => {
      const result = res as any
      if (!res) {
        return
      }
      //保存成功
      const sql = result.data
      if (sql) {
        ElMessageBox.alert(sql, t('dataList.viewSQL'), {
          customStyle: { width: '800px !important', wordBreak: 'break-all' },
          dangerouslyUseHTMLString: true,
          confirmButtonText: t('common.ok')
        })
      } else {
        ElMessage.error(t('common.dataError'))
      }
    })
  })
}

// 保存数据列表
const save = () => {
  formRef.value.validate(async (vaild) => {
    if (!vaild) {
      return
    }
    let form = Object.assign({}, state.formData)
    //校验明细记录
    if (!state.formData.cols || state.formData.cols.length == 0) {
      ElMessage.warning(t('entity.noFields'))
      return
    }
    for (let row2 of state.formData.cols) {
      const row = row2 as any
      if (row.showName == '' || row.fieldName == '' || row.colType == '') {
        ElMessage.warning(t('dataDict.rowCheck'))
        return
      }
    }
    if (nameIsRepeat()) {
      ElMessage.warning(t('dataList.repeatFieldName'))
      return
    }
    let deleteIds = ''
    if (state.deleteIds && state.deleteIds.length > 0) {
      deleteIds = state.deleteIds.join(',')
    }
    let data = { dataList: form, deleteIds: deleteIds }
    state.loading = true
    let type = 'add'
    if (form.id) {
      type = 'edit'
    }
    await saveDataList(data).then((res) => {
      const result = res as any
      state.loading = false
      if (!res) {
        return
      }
      //保存成功
      if (result.success) {
        //刷新列表
        emitter.emit('refreshDataViewList', type)
        ElMessage.success(t('group.saveSuccess'))
        if (!state.formData.entId) {
          goBack()
        }
        state.formData.seq += 1
      }
    })
  })
}

// 返回列表
const goBack = () => {
  emitter.emit('closeTag', {
    closePath: currentRoute.value.fullPath,
    backPath: state.fromPath
  })
}
/**
 * @description 当繁体中文为空时，转换简体中文为繁体中文
 * @author Elwin ZHANG
 * @date 2023-03-21 10:33
 */
const zhHKAndPinyin = async (event) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  //繁体中文为空时才自动转换
  if (state.formData.hkName.length > 0) {
    return
  }
  let data = (await getZhHKAndPinyin(text, 50)) as any
  state.formData.hkName = data.data.zhHK
  //如果英文字段为空，默认为拼音
  if (state.formData.enName.length == 0) {
    state.formData.enName = data.data.pinyin
  }
  formRef.value.clearValidate(['hkName', 'enName'])
}

/**
 * @description 当简体中文为空时，转换繁体中文为简体中文
 * @author Elwin ZHANG
 * @date 2023-03-21 10:33
 */
const zhCNAndPinyin = async (event) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  //简体中文为空时才自动转换
  if (state.formData.name.length > 0) {
    return
  }
  let data = (await getZhCNAndPinyin(text, 50)) as any
  state.formData.name = data.data.zhCN
  //如果英文字段为空，默认为拼音
  if (state.formData.enName.length == 0) {
    state.formData.enName = data.data.pinyin
  }
  formRef.value.clearValidate(['enName', 'name'])
}

/**
 * 子表输入简体中文后的事件
 * @param event 事件
 * @param row 当前行记录
 */
const inputCnText = async (event, row) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  if (row.headerHk.length > 0) {
    return
  }
  let data = (await getZhHKAndPinyin(text, 50)) as any
  row.headerHk = data.data.zhHK
  //如果英文字段为空，默认为拼音
  if (row.headerEn.length == 0) {
    row.headerEn = data.data.pinyin
  }
}

/**
 * 子表输入繁体中文后的事件
 * @param event 事件
 * @param row 当前行记录
 */
const inputHkText = async (event, row) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  if (row.headerText.length > 0) {
    return
  }
  let data = (await getZhCNAndPinyin(text, 50)) as any
  row.headerText = data.data.zhCN
  //如果英文字段为空，默认为拼音
  if (row.headerEn.length == 0) {
    row.headerEn = data.data.pinyin
  }
}

//渲染页面的接口
const init = async () => {
  const id = currentRoute.value.query.id as string
  state.deleteIds = []
  state.formData.cols = []
  state.initColIds = []
  //修改
  if (id) {
    state.formData = await getDataList(id)
    calInitIds()
    refreshFormList(state.formData.entId)
  } else {
    const moduleId = currentRoute.value.query.moduleId as string
    if (moduleId) {
      state.formData.moduleId = moduleId
    }
  }
  const fromPath = currentRoute.value.query.fromPath as string
  state.fromPath = fromPath ? fromPath : '/Develop/ListManage'
}

//计算来源实体的列ID，用于实体树控件回显
const calInitIds = () => {
  if (!state.formData || !state.formData.cols) {
    return
  }
  const cols = state.formData.cols
  if (cols.length == 0) {
    return
  }
  let arr: string[] = []
  for (const col of cols) {
    if (col.entityColId) {
      arr.push(col.entityColId)
    }
  }
  state.initColIds = arr
}

//实体列字段选择事件
const entityColCheck = (node, checked) => {
  const row = getDefaultRow()
  row.fieldName = node.fieldName
  row.fieldAlias = ''
  row.tableAlias = node.tableAlias
  const index = getRowIndex(row.fieldName, row.tableAlias)
  //选中
  if (checked) {
    if (index >= 0) {
      //防止子实体字段回显后的重复添加
      return
    }
    row.headerText = node.showName
    row.headerEn = node.enName
    row.headerHk = node.hkName
    row.dictId = node.dictId
    row.entityColId = node.colId
    const dataType = node.colType
    row.colType = dataType
    if (dataType == 'date') {
      row.dataFormat = 'YYYY-MM-DD'
    }
    if (dataType == 'datetime') {
      row.dataFormat = 'YYYY-MM-DD HH:mm:ss'
    }
    if (dataType == 'decimal') {
      row.dataFormat = '#,##0.00'
      row.textAlign = 2
    }
    state.formData.cols.push(row)
    if ('main' != node.tableAlias) {
      let txtJoin = state.formData.sqlJoin
      if (txtJoin == null) {
        txtJoin = ''
      }
      //第一次选择子实体字段
      if (txtJoin.indexOf(node.tableAlias) <= 0) {
        state.formData.sqlJoin =
          txtJoin +
          ' LEFT JOIN ' +
          node.tableName +
          ' AS ' +
          node.tableAlias +
          ' ON ' +
          node.leftTableAlias +
          '.' +
          node.leftFieldName +
          '=' +
          node.tableAlias +
          '.id'
      }
    }
  } else {
    if (index >= 0) {
      deleteRow(state.formData.cols[index], index)
    }
  }
  //console.log(checked ? '选择字段：' : '取消选择：' + JSON.stringify(node))
}

//字段名校验
const fieldNameCheck = (row) => {
  if (row.entityColId) {
    return
  }
  if (nameIsRepeat()) {
    ElMessage.warning(t('dataList.repeatFieldName'))
  }
}

//字段别名校验
const fieldAliasCheck = (row) => {
  if (!row.entityColId && row.fieldAlias == '') {
    ElMessage.warning(t('dataList.aliasCheck'))
    return
  }
  if (nameIsRepeat()) {
    ElMessage.warning(t('dataList.repeatFieldName'))
  }
}

//校验字段或别名是否有重复
const nameIsRepeat = () => {
  const nameSet = new Set()
  for (const col of state.formData.cols) {
    if (col.fieldAlias) {
      nameSet.add(col.fieldAlias)
    } else {
      nameSet.add(col.fieldName)
    }
  }
  return nameSet.size < state.formData.cols.length
}
</script>

<template>
  <div>
    <!-- 卡片表頭 -->
    <el-card class="box-card">
      <el-form
        ref="formRef"
        :model="state.formData"
        :rules="state.formRules"
        class="demo-form-inline"
        label-position="left"
        label-width="150px"
        style="padding-top: 10px"
      >
        <el-collapse v-model="state.defaultShowPanels">
          <el-collapse-item
            :title="
              $t('dataList.list') + '-' + $t('dataList.type0') + '-' + $t('dataList.groupTitle1')
            "
            name="1"
          >
            <el-row :gutter="40">
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('orderNo.module')" prop="moduleId">
                  <el-select
                    v-model="state.formData.moduleId"
                    :placeholder="$t('common.selectText')"
                    size="default"
                  >
                    <el-option
                      v-for="item in state.moduleList"
                      :key="item['moduleId']"
                      :label="item[state.modNameField]"
                      :value="item['moduleId']"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('dataList.mainEntity')" prop="entId">
                  <el-input
                    v-model="state.formData[state.entityNameField]"
                    :placeholder="$t('common.selectText')"
                    clearable
                    disabled
                    @clear="clearEnt()"
                  >
                    <template #append>
                      <el-button
                        :icon="Search"
                        @click="click2SelectEnt"
                        type="primary"
                        plain
                        style="color: darkblue"
                      />
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('menu.clientType')" prop="moduleId">
                  <el-select
                    v-model="state.formData.endType"
                    :placeholder="$t('common.selectText')"
                    size="default"
                  >
                    <el-option
                      v-for="item in state.endTypeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 第二行 -->
            <el-row :gutter="40">
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('dataList.name')" prop="name">
                  <el-input
                    v-model="state.formData.name"
                    :placeholder="$t('common.inputText') + $t('dataList.name')"
                    maxlength="30"
                    show-word-limit
                    @blur="zhHKAndPinyin($event)"
                  />
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('common.hkName')" prop="hkName">
                  <el-input
                    v-model="state.formData.hkName"
                    :placeholder="$t('common.inputText') + $t('common.hkName')"
                    maxlength="30"
                    show-word-limit
                    @blur="zhCNAndPinyin($event)"
                  />
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('common.enName')" prop="enName">
                  <el-input
                    v-model="state.formData.enName"
                    :placeholder="$t('common.inputText') + $t('common.enName')"
                    maxlength="50"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 第三行 -->
            <el-row :gutter="40">
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('dataList.pcForm')" prop="pcFormId">
                  <el-select
                    v-model="state.formData.pcFormId"
                    :placeholder="$t('common.selectText')"
                    size="default"
                    clearable
                  >
                    <el-option
                      v-for="item in state.pcFormList"
                      :key="item['fmId']"
                      :label="item[state.formNameField]"
                      :value="item['fmId']"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('dataList.pcRead')" prop="pcFormReadId">
                  <el-select
                    v-model="state.formData.pcFormReadId"
                    :placeholder="$t('common.selectText')"
                    size="default"
                    clearable
                  >
                    <el-option
                      v-for="item in state.pcFormList"
                      :key="item['fmId']"
                      :label="item[state.formNameField]"
                      :value="item['fmId']"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('common.status')" prop="status">
                  <el-input
                    v-if="state.formData.status == 1"
                    :model-value="$t('entity.status1')"
                    :disabled="true"
                  />
                  <el-input v-else :model-value="$t('entity.status0')" :disabled="true" />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 第四行 -->
            <el-row :gutter="40">
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('dataList.mbForm')" prop="mbFormId">
                  <el-select
                    v-model="state.formData.mbFormId"
                    :placeholder="$t('common.selectText')"
                    size="default"
                    clearable
                  >
                    <el-option
                      v-for="item in state.pcFormList"
                      :key="item['fmId']"
                      :label="item[state.formNameField]"
                      :value="item['fmId']"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('dataList.mbRead')" prop="mbFormReadId">
                  <el-select
                    v-model="state.formData.mbFormReadId"
                    :placeholder="$t('common.selectText')"
                    size="default"
                    clearable
                  >
                    <el-option
                      v-for="item in state.pcFormList"
                      :key="item['fmId']"
                      :label="item[state.formNameField]"
                      :value="item['fmId']"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('menu.icon')" prop="icon" class="normal_label">
                  <el-input
                    v-model="state.formData.icon"
                    :placeholder="$t('common.inputText') + $t('menu.icon')"
                    maxlength="64"
                    style="width: 100%"
                  >
                    <template #append>
                      <el-link href="https://icon-sets.iconify.design/" target="_blank">
                        {{ $t('common.query') }}</el-link
                      >
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 第五行 -->
            <el-row :gutter="40">
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('dataList.showIndex')" prop="showSerialNo">
                  <el-switch
                    v-model.number="state.formData.showSerialNo"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('dataList.selectMore')" prop="canSelectMore">
                  <el-switch
                    v-model.number="state.formData.canSelectMore"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('dataList.isLazy')" prop="isLazy">
                  <el-switch
                    v-model.number="state.formData.isLazy"
                    :active-value="1"
                    :inactive-value="0"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 第六行 -->
            <el-row :gutter="40">
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('dataList.pageSize')" prop="pageSize">
                  <el-input-number
                    v-model="state.formData.pageSize"
                    :min="5"
                    :max="200"
                    :step="5"
                    size="small"
                    style="width: 100%"
                    controls-position="right"
                  />
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('dataList.lineHeight')" prop="lineHeight">
                  <el-input v-model="state.formData.lineHeight" maxlength="20" show-word-limit />
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('common.remark')" prop="remark">
                  <el-input v-model="state.formData.remark" maxlength="65000" />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 第七行 -->
            <el-row :gutter="40">
              <el-col :sm="24" :md="8">
                <el-form-item :label="$t('form.ver')" prop="ver">
                  <el-input v-model="state.formData.ver" disabled />
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="8">
                <el-form-item
                  :label="$t('common.updateBy')"
                  prop="updateBy"
                  v-if="state.formData.id"
                >
                  <el-input v-model="state.formData.updateBy" disabled />
                </el-form-item>
              </el-col>
              <el-col :sm="24" :md="8">
                <el-form-item
                  :label="$t('common.updateTime')"
                  prop="updateTime"
                  v-if="state.formData.id"
                >
                  <el-input v-model="state.formData.updateTime" disabled />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item :title="$t('dataList.colConfig')" name="2">
            <el-container>
              <el-aside width="200px">
                <EntityTree
                  :ent-id="state.formData.entId"
                  :init-selected="state.initColIds"
                  style="width: 200px; max-height: 480px; overflow-y: auto"
                  @node-check="entityColCheck"
                />
              </el-aside>
              <el-main>
                <div style="margin: -12px -20px -12px -12px">
                  <el-row>
                    <el-col :span="18">
                      <el-alert
                        :title="$t('dataList.selectColTip')"
                        type="warning"
                        :closable="false"
                        style="font-size: 12px; height: 25px"
                      />
                    </el-col>
                    <el-col :span="6">
                      <div style="text-align: right; margin-bottom: 5px">
                        <el-button type="success" size="small" plain @click="addRow()">
                          <Icon icon="material-symbols:add-circle-rounded" />
                          <span>{{ t('dataList.addCol') }}</span>
                        </el-button>
                      </div>
                    </el-col>
                  </el-row>

                  <!-- 子表控件 -->
                  <el-table
                    :data="state.formData.cols"
                    tooltip-effect="light"
                    class="colTable"
                    stripe
                    default-expand-all
                    border
                    :height="452"
                    size="small"
                    :default-sort="{ prop: 'colOrder', order: 'ascending' }"
                    :header-cell-style="{
                      background: 'var(--el-color-primary-light-9)',
                      color: '#409eff'
                    }"
                  >
                    <el-table-column type="index" width="35" fixed>
                      <template #header>
                        <div style="margin-bottom: -10px">
                          <Icon
                            icon="ant-design:field-number-outlined"
                            size="24"
                            :title="$t('common.number')"
                        /></div>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="tableAlias"
                      :label="$t('dataList.tableAlias')"
                      min-width="105"
                      fixed
                      align="center"
                    >
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.tableAlias"
                          :maxlength="64"
                          :disabled="!!scope.row.entityColId"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="fieldName"
                      :label="'*' + $t('dataList.fieldName')"
                      min-width="120"
                      fixed
                      align="center"
                    >
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.fieldName"
                          :maxlength="64"
                          @blur="fieldNameCheck(scope.row)"
                          :disabled="!!scope.row.entityColId"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="fieldAlias"
                      :label="$t('dataList.fieldAlias')"
                      min-width="105"
                      align="center"
                    >
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.fieldAlias"
                          :maxlength="64"
                          @blur="fieldAliasCheck(scope.row)"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="colType"
                      :label="'*' + $t('entity.colType')"
                      min-width="105"
                      align="center"
                    >
                      <template #default="scope">
                        <el-select
                          v-model="scope.row.colType"
                          size="default"
                          :disabled="!!scope.row.entityColId"
                        >
                          <el-option
                            v-for="item in state.dataTypes"
                            :key="item['value']"
                            :label="item['name']"
                            :value="item['value']"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="headerText"
                      :label="'*' + $t('dataList.colTitle')"
                      min-width="110"
                      align="center"
                    >
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.headerText"
                          :maxlength="30"
                          @blur="inputCnText($event, scope.row)"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="headerHk"
                      :label="$t('dataList.colTitleHk')"
                      min-width="110"
                      align="center"
                    >
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.headerHk"
                          :maxlength="30"
                          @blur="inputHkText($event, scope.row)"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="headerEn"
                      :label="$t('dataList.colTitleEn')"
                      min-width="110"
                      align="center"
                    >
                      <template #default="scope">
                        <el-input v-model="scope.row.headerEn" :maxlength="50" />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="colOrder"
                      align="right"
                      :label="$t('common.sort')"
                      width="70"
                      sortable
                    >
                      <template #default="scope">
                        <el-input
                          v-model.number="scope.row.colOrder"
                          :maxlength="9"
                          type="number"
                          :input-style="{ 'text-align': 'right' }"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column prop="dataFormat" min-width="100" align="center">
                      <template #header>
                        <span title='"0.00%"、"￥#,##0.00"、"YYYY-MM-DD HH:mm:ss"'
                          >{{ $t('dataList.format') }}☀</span
                        >
                      </template>
                      <template #default="scope">
                        <el-input v-model="scope.row.dataFormat" :maxlength="20" />
                      </template>
                    </el-table-column>
                    <el-table-column
                      :label="$t('dataList.align')"
                      prop="textAlign"
                      min-width="90"
                      align="center"
                    >
                      <template #default="scope">
                        <el-select
                          v-model="scope.row.textAlign"
                          :placeholder="$t('common.selectText')"
                          size="default"
                        >
                          <el-option :label="$t('dataList.align0')" :value="0" />
                          <el-option :label="$t('dataList.align1')" :value="1" />
                          <el-option :label="$t('dataList.align2')" :value="2" />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column prop="colWidth" min-width="80" align="center">
                      <template #header>
                        <span :title="$t('dataList.widthTip')">{{ $t('dataList.colWidth') }}☀</span>
                      </template>
                      <template #default="scope">
                        <el-input v-model="scope.row.colWidth" :maxlength="20" />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="fontSize"
                      :label="$t('dataList.fontSize')"
                      min-width="80"
                      align="center"
                    >
                      <template #default="scope">
                        <el-input v-model="scope.row.fontSize" :maxlength="10" />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="fontColor"
                      :label="$t('dataList.fontColor')"
                      min-width="80"
                      align="center"
                    >
                      <template #default="scope">
                        <el-input v-model="scope.row.fontColor" :maxlength="20" />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="bgColor"
                      :label="$t('dataList.backColor')"
                      min-width="80"
                      align="center"
                    >
                      <template #default="scope">
                        <el-input v-model="scope.row.bgColor" :maxlength="20" />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="isFilter"
                      :label="$t('dataList.canFilter')"
                      width="58"
                      align="center"
                    >
                      <template #default="scope">
                        <el-switch
                          v-model.number="scope.row.isFilter"
                          :active-value="1"
                          :inactive-value="0"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="isSort"
                      :label="$t('dataList.canSort')"
                      width="58"
                      align="center"
                    >
                      <template #default="scope">
                        <el-switch
                          v-model.number="scope.row.isSort"
                          :active-value="1"
                          :inactive-value="0"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="isFixed"
                      :label="$t('dataList.fixed')"
                      width="58"
                      align="center"
                    >
                      <template #default="scope">
                        <el-switch
                          v-model.number="scope.row.isFixed"
                          :active-value="1"
                          :inactive-value="0"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="isExport"
                      :label="$t('dataList.canExport')"
                      width="58"
                      align="center"
                    >
                      <template #default="scope">
                        <el-switch
                          v-model.number="scope.row.isExport"
                          :active-value="1"
                          :inactive-value="0"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="isMobile"
                      :label="$t('entity.mainColTip')"
                      width="90"
                      align="center"
                    >
                      <template #default="scope">
                        <el-switch
                          v-model.number="scope.row.isMobile"
                          :active-value="1"
                          :inactive-value="0"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="isLink"
                      :label="$t('dataList.isLink')"
                      width="58"
                      align="center"
                    >
                      <template #default="scope">
                        <el-switch
                          v-model.number="scope.row.isLink"
                          :active-value="1"
                          :inactive-value="0"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="linkUrl"
                      :label="$t('dataList.linkUrl')"
                      min-width="100"
                      align="center"
                    >
                      <template #default="scope">
                        <el-input
                          v-model="scope.row.linkUrl"
                          :maxlength="100"
                          v-if="scope.row.isLink == 1"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="op"
                      align="center"
                      :label="$t('common.operation')"
                      width="50"
                      fixed="right"
                    >
                      <template #default="scope">
                        <el-button
                          type="danger"
                          size="small"
                          plain
                          circle
                          :title="$t('common.delete')"
                          @click="deleteRow(scope.row, null)"
                        >
                          <el-icon>
                            <Delete />
                          </el-icon>
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-main>
            </el-container>
          </el-collapse-item>
          <el-collapse-item :title="$t('dataList.sqlConfig')" name="3">
            <el-row :gutter="40">
              <el-col :span="24">
                <el-form-item :label="$t('dataList.joinClause')" prop="sqlJoin">
                  <el-input
                    v-model="state.formData.sqlJoin"
                    autosize
                    type="textarea"
                    maxlength="65000"
                  />
                </el-form-item>
                <el-form-item :label="$t('dataList.whereClause')" prop="sqlWhere">
                  <el-input
                    v-model="state.formData.sqlWhere"
                    autosize
                    type="textarea"
                    maxlength="65000"
                  />
                </el-form-item>
                <el-form-item :label="$t('dataList.orderClause')" prop="sqlOderBy">
                  <el-input
                    v-model="state.formData.sqlOderBy"
                    autosize
                    type="textarea"
                    maxlength="65000"
                  />
                </el-form-item>
                <el-form-item :label="$t('dataList.preSql')" prop="beforeSql">
                  <el-input
                    v-model="state.formData.beforeSql"
                    autosize
                    type="textarea"
                    maxlength="65000"
                  />
                </el-form-item>
                <el-form-item :label="$t('dataList.delValidSql')" prop="sqlBeforeDel">
                  <el-input
                    v-model="state.formData.sqlBeforeDel"
                    autosize
                    type="textarea"
                    maxlength="65000"
                  />
                </el-form-item>
                <el-form-item :label="$t('dataList.afterDelSql')" prop="sqlAfterDel">
                  <el-input
                    v-model="state.formData.sqlAfterDel"
                    autosize
                    type="textarea"
                    maxlength="65000"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item :title="$t('dataList.buttonConfig')" name="4">待开发 </el-collapse-item>
          <el-collapse-item :title="$t('dataList.authConfig')" name="5">待开发 </el-collapse-item>
        </el-collapse>
      </el-form>
      <div class="detailFooter">
        <el-button
          type="primary"
          plain
          @click="save()"
          :loading="state.loading"
          v-if="state.formData.isBuildIn != 1"
        >
          <el-icon><Check /></el-icon>&nbsp;{{ $t('common.save') }}
        </el-button>
        <el-button plain @click="showSql()" v-if="state.formData.id">
          <Icon icon="ant-design:console-sql-outlined" />&nbsp;{{ $t('dataList.viewSQL') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="preview(state.formData.id)"
          v-if="state.formData.id"
        >
          <Icon icon="icon-park-outline:preview-open" />&nbsp;{{ $t('dataList.preview') }}
        </el-button>
        <el-button
          type="success"
          plain
          :loading="state.publishLoading"
          @click="publish()"
          v-if="state.formData.id && state.formData.status != 4 && state.formData.isBuildIn == 0"
          :title="$t('entity.publishBtnTip')"
        >
          <Icon icon="fluent:database-arrow-up-20-filled" />&nbsp;<span
            v-if="state.formData.status == 0"
            >{{ $t('entity.publish') }}</span
          ><span v-if="state.formData.status == 1">{{ $t('entity.rePublish') }}</span>
        </el-button>
        <el-button type="info" plain @click="goBack">
          <el-icon><Close /></el-icon>&nbsp;{{ $t('form.close') }}
        </el-button>
      </div>
    </el-card>

    <!-- 选择引用实体选择对话框 -->
    <EntityDialog
      v-model="state.entityDialogVisible"
      @selected="selectEntity"
      :module-id="state.formData.moduleId"
      :ent-id="state.formData.entId"
      @cancel="state.entityDialogVisible = false"
      width="850px"
    />
  </div>
</template>
<style lang="less" scoped>
.box-card {
  .card-header {
    font-size: 16px;
    letter-spacing: 1px;
  }
  :deep(.el-input) {
    font-size: 12px;
  }
  :deep(.el-textarea__inner) {
    height: 85px;
    font-size: 12px;
  }
}
:deep(.el-input__inner) {
  &::placeholder {
    font-size: 12px;
  }
}
:deep(.el-message-box .el-textarea__inner) {
  height: 300px;
}

.el-select-dropdown__item {
  font-size: 12px;
}
input {
  height: 28px;
  border: 1px solid #ddd;
  padding: 5px;
  width: 100%;
}
.required {
  color: red;
}

.colTable {
  border-color: #a0cfff;
  font-size: 12px;
  width: 100%;
}
.inputRequired {
  width: 90%;
  margin-left: 3px;
}
</style>
